package com.yonyou.cyxdms.basedata.service.util;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import com.xiaoleilu.hutool.util.StrUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;

/**
 * EASYPOI工具类
 * 导出使用字典进行转换时相关实体的属性注解加入dict对应值(其值为字典表中type字段)：
 * 例:@Excel(name = "计划状态", dict = "6024")
 *
 * @author lyz
 * @date 2020/11/17
 */
public class EasyPoiUtil {

    private static final Logger logger = LoggerFactory.getLogger(com.yonyou.cyxdms.basedata.service.util.EasyPoiUtil.class);

    /**
     * 使用response写出Excel
     *
     * @param sheetName 页签名
     * @param titleName 标题
     * @param dataList  数据
     * @param poClass   PO的CLASS
     * @param fileName  文件名(.xls格式的)
     * @author lyz
     * @date 2020/11/17
     */
    public static <T> void exportExcelResponse(String sheetName, String titleName, List<T> dataList,
                                               Class<T> poClass, String fileName, HttpServletResponse response) throws IOException {
        OutputStream outputStream = null;
        try {
            ExportParams exportParams = new ExportParams();
            exportParams.setSheetName(sheetName);
            if (StrUtil.isNotEmpty(titleName)) {
                exportParams.setTitle(titleName);
            }
            exportParams.setDictHandler(new GlobalExcelDictHandler());
            Workbook workbook = ExcelExportUtil.exportExcel(exportParams, poClass, dataList);
            response.reset();
            response.setCharacterEncoding("UTF-8");
            response.setHeader("content-Type", "application/vnd.ms-excel");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            outputStream = response.getOutputStream();
            workbook.write(outputStream);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (outputStream != null) {
                    outputStream.flush();
                    outputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 使用流写出excel
     * 注意关流
     * 文件名后缀为 .xls
     *
     * @param sheetName    页签名
     * @param titleName    标题
     * @param dataList     数据
     * @param poClass      PO的CLASS
     * @param outputStream 输出流
     * @author lyz
     * @date 2020/11/17
     */
    public static <T> void exportExceloutPut(String sheetName, String titleName, List<T> dataList,
                                             Class<T> poClass, OutputStream outputStream) throws IOException {
        ExportParams exportParams = new ExportParams();
        exportParams.setSheetName(sheetName);
        exportParams.setTitle(titleName);
        exportParams.setDictHandler(new GlobalExcelDictHandler());
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, poClass, dataList);
        workbook.write(outputStream);
    }

    /**
     * 文件转存
     *
     * @param uploadDir 存储文件夹
     * @param file      上传文件
     * @param fileName  文件名
     * @author lyz
     * @date 2020/11/17
     */
    public String executeUpload(String uploadDir, MultipartFile file, String fileName) throws Exception {
        //文件后缀名
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        //上传文件名
        String filename = fileName + suffix;
        //服务器端保存的文件对象
        File serverFile = new File(uploadDir + filename);
        //将上传的文件写入到服务器端文件内
        file.transferTo(serverFile);

        return filename;
    }

    /**
     * 按路径导入文件
     *
     * @param filePath   上传路径
     * @param titleRows  列表头行数
     * @param headerRows 标题行数
     * @param pojoClass  解析用实体
     * @author lyz
     * @date 2020/11/17
     */
    public static <T> List<T> importExcel(String filePath, Integer titleRows, Integer headerRows, Class<T> pojoClass) {
        if (StringUtils.isBlank(filePath)) {
            return null;
        }
        ImportParams params = new ImportParams();
        params.setTitleRows(titleRows);
        params.setHeadRows(headerRows);
        params.setDictHandler(new GlobalExcelDictHandler());
        List<T> list = null;
        try {
            list = ExcelImportUtil.importExcel(new File(filePath), pojoClass, params);
        } catch (Exception e) {
            logger.error("到处Excel异常： {}", e.getMessage());
        }
        return list;
    }

    /**
     * 按上传文件导入excel
     *
     * @param file       上传文件
     * @param titleRows  列表头行数
     * @param headerRows 标题行数
     * @param pojoClass  解析用实体
     * @author lyz
     * @date 2020/11/17
     */
    public static <T> List<T> importExcel(MultipartFile file, Integer titleRows, Integer headerRows, Class<T> pojoClass) {
        if (file == null) {
            return null;
        }
        ImportParams params = new ImportParams();
        params.setTitleRows(titleRows);
        params.setHeadRows(headerRows);
        params.setDictHandler(new GlobalExcelDictHandler());
        List<T> list = null;
        try {
            list = ExcelImportUtil.importExcel(file.getInputStream(), pojoClass, params);
        } catch (Exception e) {
            logger.error("到处Excel异常： {}", e.getMessage());
        }
        return list;
    }

}
